# coding: utf-8

import uuid
from datetime import date, datetime

from sqlalchemy import text
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin, AnonymousUserMixin

from ..extensions import db, login_manager
from ..models import BaseModel
from .constant import AdminEvent, AdminRole


class AdminUser(UserMixin, BaseModel):
    __tablename__ = 'admin'

    username = db.Column(
        db.String(64, 'utf8mb4_unicode_ci'),
        nullable=False,
        server_default=text("''"),
        default='',
    )
    password = db.Column(
        db.String(128, 'utf8mb4_unicode_ci'),
        nullable=False,
        server_default=text("''"),
        default='',
    )
    nickname = db.Column(
        db.String(128),
        nullable=False,
        server_default=text("''"),
        default='',
    )
    agent_id = db.Column(
        db.String(128),
        nullable=False,
        server_default=text("''"),
        default='',
    )
    # 是否系统管理员，此类角色可编辑其他管理员信息
    is_administrator = db.Column(
        db.Boolean(),
        server_default=text("false"),
        default=False,
    )
    # 是否联通云客服, 默认否
    is_lt_cs = db.Column(db.Boolean, default=False, server_default=text("false"))
    role_id = db.Column(db.Integer, server_default=text("'0'"), default=0)
    # 座席状态
    agent_state = db.Column(db.Integer, server_default=text("'0'"), default=0)
    # 座席签入时间
    agent_login_time = db.Column(db.DateTime(), nullable=True)
    session_token = db.Column(db.String(32), default='', server_default=text("''"), index=True)

    # 七陌客服账号密码
    seven_moor_account = db.Column(db.String(128), nullable=True,
        server_default=text("''"), default='',
    )
    seven_moor_password = db.Column(db.String(128), nullable=True,
        server_default=text("''"), default='',
    )

    @property
    def pwd(self):
        raise AttributeError('password is not a readable attribute')

    @pwd.setter
    def pwd(self, password):
        self.password = generate_password_hash(password)

    def verify_pwd(self, password):
        return check_password_hash(self.password, password)

    @property
    def is_deleted_display(self):
        return '是' if self.deleted_at else '否'

    @property
    def is_administrator(self):
        return self.role_id == AdminRole.ADMINISTRATOR.value

    @property
    def is_agent(self):
        return self.role_id == AdminRole.AGENT.value

    @property
    def is_sem(self):
        return self.role_id == AdminRole.SEM.value

    @property
    def is_market(self):
        return self.role_id == AdminRole.MARKET.value

    @property
    def is_operation(self):
        return self.role_id == AdminRole.OPERATION.value

    @property
    def is_developer(self):
        return self.role_id == AdminRole.DEVELOPER.value

    @property
    def is_product(self):
        return self.role_id == AdminRole.PRODUCT.value

    @property
    def role_display(self):
        return AdminRole(self.role_id).display

    def get_id(self):
        """
        created by chenhj at 2018/6/14
        用于load_user 方法获取session_token用
        """
        return self.session_token

    def upgrade_session_token(self):
        """
        created by chenhj at 2018/6/14

        """
        self.session_token = uuid.uuid4().hex


class AnonymousUser(AnonymousUserMixin):
    pass

login_manager.anonymous_user = AnonymousUser


@login_manager.user_loader
def load_user(session_token):
    return AdminUser.query.filter(
        AdminUser.session_token == session_token,
        AdminUser.deleted_at == 0
    ).first()


class AdminEventStat(BaseModel):
    """
    created by chenhj at 2017/8/28
    管理员某些功能事件统计
    """
    __tablename__ = 'admin_event_stat'

    search_keys = ('event', 'nickname')
    filter_dict = {
        'date': ()
    }

    admin_id = db.Column(db.Integer, default=0)
    nickname = db.Column(db.String(128), default='')
    event = db.Column(db.String(64))
    date = db.Column(db.Date, default=date.today)
    count = db.Column(db.Integer, default=0)

    @property
    def event_display(self):
        return AdminEvent(self.event).display

    def __init__(self, **kwargs):
        super(AdminEventStat, self).__init__(**kwargs)
        user = AdminUser.get_by_id(kwargs['admin_id'])
        self.nickname = user.nickname


class PublishDemandLog(BaseModel):
    """
    created by chenhj at 2017/12/5
    发布项目操作日志
    """
    __tablename__ = 'publish_demand_log'

    filter_dict = {
        'admin_id': (),
        'demand_id': (),
    }

    admin_id = db.Column(db.ForeignKey('admin.id'))
    demand_id = db.Column(db.ForeignKey('demand.id'))
    old_demand_status = db.Column(db.Integer)
    new_demand_status = db.Column(db.Integer)
    published_count = db.Column(db.Integer)
    published_at = db.Column(db.Integer)
    notice_way = db.Column(db.Integer)
    notice_pay = db.Column(db.Boolean)
    # 派单人数
    dispatch_count = db.Column(db.Integer, server_default=text("'0'"))

    admin = db.relationship('AdminUser')

    @property
    def published_datetime(self):
        return datetime.fromtimestamp(self.published_at)

    @property
    def old_demand_status_display(self):
        from app.op.constant import DemandStatus
        return DemandStatus(self.old_demand_status).display

    @property
    def new_demand_status_display(self):
        from app.op.constant import DemandStatus
        return DemandStatus(self.new_demand_status).display

    @property
    def notice_way_display(self):
        from app.op.constant import DemandNoticeWay
        return DemandNoticeWay(self.notice_way).display
